package com.qkjia.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkjia.common.exception.Assert;
import com.qkjia.common.result.ResponseEnum;
import com.qkjia.srb.core.enums.BorrowInfoStatusEnum;
import com.qkjia.srb.core.enums.BorrowerStatusEnum;
import com.qkjia.srb.core.enums.UserBindEnum;
import com.qkjia.srb.core.mapper.*;
import com.qkjia.srb.core.pojo.entity.BorrowInfo;
import com.qkjia.srb.core.pojo.entity.Borrower;
import com.qkjia.srb.core.pojo.entity.IntegralGrade;
import com.qkjia.srb.core.pojo.entity.UserInfo;
import com.qkjia.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.qkjia.srb.core.pojo.vo.BorrowerDetailVO;
import com.qkjia.srb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qkjia.srb.core.service.BorrowerService;
import com.qkjia.srb.core.service.DictService;
import com.qkjia.srb.core.service.LendService;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author 赵乾坤
 * @since 2021-11-01
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private IntegralGradeMapper integralGradeMapper;
    @Resource
    private DictService dictService;
    @Resource
    private BorrowerMapper borrowerMapper;
    @Resource
    private BorrowerService borrowerService;
    @Resource
    private LendService lendService;



    /**
     *  获取借款额度
     * @param userId 用户id
     * @return
     */
    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据积分查询额度
        QueryWrapper<IntegralGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("integral_start", integral);
        queryWrapper.ge("integral_end", integral);
        IntegralGrade integralGradeConfig = integralGradeMapper.selectOne(queryWrapper);
        if(integralGradeConfig == null){
            return new BigDecimal("0");
        }
        return integralGradeConfig.getBorrowAmount();
    }

    /**
     * 提交借款申请
     * @param borrowInfo 借款信息表对象
     * @param userId 用户id
     */
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        // 获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);
        // 判断用户绑定状态
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR);
        // 判断用户信息是否审批通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_AMOUNT_ERROR);
        // 判断借款额度是否足够
        // 获取借款额度
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),
        ResponseEnum.USER_AMOUNT_LESS_ERROR);
        //存储数据
        borrowInfo.setUserId(userId);
        //百分比转成小数
        // divide 对他做除一百的操作
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);



    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id", userId);
        // 此时下面的objects 里面 存放的是 status字段
        List<Object> objects = baseMapper.selectObjs(borrowInfoQueryWrapper);
        if (objects.size() == 0) {
            // 借款人尚未提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = (Integer) objects.get(0);
        return status;
    }

    @Override
    public List<BorrowInfo> selectList() {
        // 组装dict的数据字典
        List<BorrowInfo> borrowInfoList  = baseMapper.selectBorrowInfoList();
        borrowInfoList.forEach( borrowInfo -> {
            extracted(borrowInfo);
        });
        return borrowInfoList;
    }

    /**
     * 组装数据 查询dict
     * @param borrowInfo
     */
    private void extracted(BorrowInfo borrowInfo) {
        // dict表 value和code 拿数据
        // 还款方式 1-等额本息 2-等额本金 3-每月还息一次还本 4-一次还本
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        // 资金用途
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        // 状态（0：未提交，1：审核中， 2：审核通过， -1：审核不通过）
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {
        // 查询借款对象
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        // 组装数据
        this.extracted(borrowInfo);
        // 根据user_id获取借款人对象
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<Borrower>();
        borrowerQueryWrapper.eq("user_id", borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(borrowerQueryWrapper);
        // 组装借款人对象
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());
        // 组装数据
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo", borrowInfo);
        result.put("borrower", borrowerDetailVO);
        return result;
    }


    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        // 更改BorrowerInfo 状态
        Long borrowInfoId = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);
        // 审核通过产生标的 lend
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            // 创建新的标的
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }


    }
}
